package com.example.learnapp;

import android.graphics.ImageFormat;
import android.hardware.Camera;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import java.io.IOException;

public class Video_Activity extends AppCompatActivity {

    private static String TAG="Video_Activity";
    private Button open_camera,play_video,close_camera;
    private SurfaceView surfaceView;
    private SurfaceHolder surfaceHolder;
    private Camera camera;
    private MediaRecorder videoRecorder;

    private String myVideofilepath = "sdcard/myvideo.mp4";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video);

        videoRecorder = new MediaRecorder();
        surfaceView = findViewById(R.id.surfaceView_video);
        surfaceHolder = surfaceView.getHolder();
        surfaceHolder.addCallback(mSurfaceCallback);//设置Holder的回调

        init_viiew();
    }


    private SurfaceHolder.Callback mSurfaceCallback = new SurfaceHolder.Callback() {
        @Override
        public void surfaceCreated(@NonNull SurfaceHolder holder) {
            Log.i(TAG, "surface destroyed");
            surfaceHolder = holder;
        }

        @Override
        public void surfaceChanged(@NonNull SurfaceHolder holder, int format, int width, int height) {
            Log.i(TAG, "surface changed.");
            surfaceHolder = holder;
            openCamera();//不自动回调预览
        }

        @Override
        public void surfaceDestroyed(@NonNull SurfaceHolder holder) {
            Log.i("camera", "surface destroyed.");
            surfaceHolder = null;
            stopRecording();
            releaseCamera();
        }
    };

    private void init_viiew() {
        open_camera = (Button) this.findViewById(R.id.open_camera);
        play_video = (Button) this.findViewById(R.id.play_video);
        close_camera = (Button) this.findViewById(R.id.close_camera);

        open_camera.setOnClickListener(new View.OnClickListener( ) {
            @Override
            public void onClick(View v) {
                openCamera();
            }
        });
        play_video.setOnClickListener(new View.OnClickListener( ) {
            @Override
            public void onClick(View v) {
                beginRecording();
            }
        });

        close_camera.setOnClickListener(new View.OnClickListener( ) {
            @Override
            public void onClick(View v) {
                stopRecording();
            }
        });
    }


    protected void stopRecording(){
        Log.i("videoRecorder", "stopRecording...");
        if (videoRecorder != null) {
            videoRecorder.stop( );
            videoRecorder.reset( );
            videoRecorder.release( );
            videoRecorder = null;
            camera.lock( );
        }
    }

    private void releaseCamera(){
        if(camera !=null){
            camera.release();
            camera=null;
        }
    }

    protected void beginRecording(){
        Log.i(TAG, "beginRecording");
        //给摄像头解锁
        camera.unlock();
        //MediaRecorder获取到摄像头的访问权
        videoRecorder.setCamera(camera);
        //设置视频录制过程中所录制的音频来自手机的麦克风
        videoRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        //设置视频源为摄像头
        videoRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        //设置视频录制的输出文件为3gp文件
        videoRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        //设置音频编码方式为AAC
        videoRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
        //设置录制的视频编码为H.264
        videoRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
        //videoRecorder.setVideoSize(176, 144);
        videoRecorder.setVideoSize(1280, 720);
        videoRecorder.setVideoEncodingBitRate((int) ((3) * 1024 * 1024));//设置编码比特率,不设置会使视频图像模糊
        videoRecorder.setVideoFrameRate(30);
        videoRecorder.setCaptureRate(20);
        videoRecorder.setMaxDuration(60 * 1000);

        if (!checkSDCard()) {
            Log.e("videoRecorder", "未找到SD卡!");
            return;
        }
        videoRecorder.setOutputFile(myVideofilepath);
        videoRecorder.setPreviewDisplay(surfaceHolder.getSurface());
        try {
            videoRecorder.prepare();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        videoRecorder.start();
    }

    private void openCamera(){
        Log.i("videoRecorder", "openCamera.");
        camera =Camera.open();
        Camera.Parameters parameters = camera.getParameters();
//        Camera.Size size = getBestPreviewSize(1080, 1920, parameters);
//        if(size != null){
//            parameters.setPreviewSize(size.width,size.height);
//        }
        parameters.setFocusMode(Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO);
        parameters.setPreviewFrameRate(30);
        parameters.setPreviewFormat(ImageFormat.NV21); //设置数据格式
        parameters.setRecordingHint(true);
        camera.setDisplayOrientation(90);
        //camera.setPreviewCallback(this);
        camera.setParameters(parameters);
        //绑定Surface并开启预览
        try {
            camera.setPreviewDisplay(surfaceHolder);
        } catch (IOException e) {
            e.printStackTrace( );
        }
        camera.startPreview();
    }

    private boolean checkSDCard() {
        // 判断SD存储卡是否存在
        if (android.os.Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            return true;
        } else {
            return false;
        }
    }


}